var submitObj = {
    name: "",
    sex: "",
    phone: "",
    idCard: "",
    age: "",
    communityId: "",
    building: "",
    room: "",
    pictureId: ""
}; // 要提交的数据对象

var communityIdItems = []; // 存放小区下拉框数据
var pictureIdArr = new Array(); // 图片ID数组
var maxCount = 1; // 最大图片数量

/**
 * 绑定提交按钮的点击事件
 */
$(document).on("click", "#submit", function() {
    checkAndSubmit()
});

/**
 * 校验通过后提交
 */
function checkAndSubmit() {
    if (validateNull($("#name").val())) {
        $.toptip("请输入姓名", "warning");
        return;
    } else {
        submitObj.name = $("#name").val();
    }

    if (validateNull(submitObj.sex)) {
        $.toptip("请选择性别", "warning");
        return;
    }

    if (validateNull($("#age").val())) {
        $.toptip("请输入年龄", "warning");
        return;
    } else {
        submitObj.age = $("#age").val();
    }

    if (validateNull($("#phone").val()) ||!/1[3|4|5|7|8]\d{9}/.test($("#phone").val())) {
        $.toptip("请输入正确的手机号", "warning");
        return;
    } else {
        submitObj.phone = $("#phone").val();
    }

    if (validateNull($("#idCard").val())) {
        $.toptip("请输入身份证号", "warning");
        return;
    } else {
        submitObj.idCard = $("#idCard").val();
    }

    if (validateNull(submitObj.communityId)) {
        $.toptip("请选择小区名称", "warning");
        return;
    }

    if (validateNull($("#building").val())) {
        $.toptip("请输入楼栋号", "warning");
        return;
    } else {
        submitObj.building = $("#building").val();
    }

    if (validateNull($("#room").val())) {
        $.toptip("请输入详细地址", "warning");
        return;
    } else {
        submitObj.room = $("#room").val();
    }

    if (validateNull(pictureIdArr)) {
        $.toptip("请上传头像文件", "warning");
        return;
    } else {
        submitObj.pictureId = pictureIdArr.join(",");
    }

    submitConfirm();
}

/**
 * 提交
 */
function submitConfirm() {
    // // 开启等待层
    $.showLoading("提交信息中...");

    // 发送ajax请求保存用户信息
    $.ajax({
        url: baseUrl + "/public-user/save",
        data: JSON.stringify(submitObj),
        contentType: "application/json;charset=UTF-8",
        type: "post",
        dataType: "JSON",
        success: function (res) {
            if (res.code == 200) {
                // $.toast(res.message)
                window.location.href = baseUrl + "/public-user/user-add-success"
            } else {
                $.toast(res.message, 'text');
            }
        },
        error: function (res) {
            // $.toast("系统异常，请稍后重试", 'forbidden');
            window.location.href = baseUrl + "/public-user/user-add-fail"
        },
        complete: function () {
            // 关闭等待层
            $.hideLoading();
        }
    })
}

// 校验是否为空
function validateNull(value) {
    if (value == "" || value == undefined || value == null || value.length === 0) {
        return true;
    }
}

var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>';
/**
 * 图片处理
 */
function initImg() {
    // 允许上传的图片类型
    var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', "image/PNG", "image/JPG", "image/JEPG"];
    // 最大上传10M
    var maxSize = 1024 * 1024 * 10;

    var $gallery = $("#gallery"),
        $galleryImg = $("#galleryImg"),
        $uploaderInput = $("#uploaderInput"),
        $uploaderFiles = $("#uploaderFiles");

    $uploaderInput.on("change", function(e){
        var src, url = window.URL || window.webkitURL || window.mozURL;
        var files = e.target.files;
        // 如果没有选中文件，直接返回
        if (files.length === 0) {
            return;
        }
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];

            // 如果类型不在允许范围内
            if (allowTypes.indexOf(file.type) === -1) {
                $.toptip("该类型不允许上传", "warning");
                continue;
            }

            if (file.size > maxSize) {
                $.toptip("图片太大，不允许上传", "warning");
                continue;
            }

            if (pictureIdArr.length >= maxCount) {
                $.toptip("最多只能上传" + maxCount + "张图片", "warning");
                return;
            }

            if (url) {
                src = url.createObjectURL(file);
            } else {
                src = e.target.result;
            }

            $uploaderFiles.append($(tmpl.replace('#url#', src)));
            // 选择即上传
            uploadImg(file);
        }

    });

    var index; // 第几张图片
    var category; //那个类别
    var imgid; // 图片ID

    // 图片缩略图元素单击，展示图片预览视图
    $uploaderFiles.on("click", "li", function(){
        index = $(this).index();
        category = "headImg";
        imgid = $(this).attr("id");
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
    });
    // 预览界面单击退出
    $gallery.on("click", function(){
        $gallery.fadeOut(100);
    });

    //删除图片(根据类别和序号处理)
    $(".weui-gallery__del").click(function () {
        RemoveImg(); //普通图片快速移除
    });

    //移除对应类别的图片
    function RemoveImg() {
        if (category == "headImg") {
            $uploaderFiles.find("li").eq(index).remove();
            pictureIdArr.splice(index, 1);
            $(".weui-uploader__info").text(pictureIdArr.length + "/" + maxCount);
        } else {
            alert("没有对应类型");
        }
    };

    function uploadImg(file) {
        var formData = new FormData();
        formData.append("file", file);
        // 开启等待层
        $.showLoading("图片上传中...");

        $.ajax({
            url: baseUrl + '/picture/uploadImg',
            type: 'POST',
            data: formData,
            dataType: "json",
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            success: function(res) {
                if (res.code == 200) {
                    pictureIdArr.push(res.data.id);
                    $.toast("图片上传成功");
                }
            },
            error: function(res) {
                // error了需要将页面的图片移除
                $.toast("图片上传失败，请重新上传", "forbidden");
                // 移除ul最后一个li
                var liElement = $uploaderFiles.getElementsByTagName("li");
                $uploaderFiles.removeChild(liElement[liElement.length - 1])
            },
            complete: function () {
                $(".weui-uploader__info").text(pictureIdArr.length + "/" + maxCount);
                // 关闭等待层
                $.hideLoading();
            }
        });
    }
}

/**
 * 初始化下拉框
 */
function initSelect() {
    $("#sex").select({
        title: '请选择性别',
        items: [
            {
                title: "男",
                value: "1",
            },
            {
                title: "女",
                value: "2",
            }
        ],
        onChange: function (item) {
            submitObj.sex = item.values;
        }
    });



    $.ajax({
        url: baseUrl + '/community/queryAll',
        type: 'POST',
        async: true,
        dataType: "json",
        success: function (res) {
            let data=res.data;
            for (var i = 0; i < data.length; i++) {
                communityIdItems.push({title:data[i].name, value:data[i].id});
            }
            $("#communityId").select({
                title: '请选择小区',
                items: communityIdItems,
                onChange: function (item) {
                    submitObj.communityId = item.values;
                }
            });
        }
    });

    initUserInfo();
}

/**
 * 初始化用户信息
 */
function initUserInfo() {
    $.showLoading("用户信息获取中");
    $.ajax({
        url: baseUrl + '/public-user/info',
        type: 'GET',
        async: true,
        dataType: "json",
        success: function(res) {
            if (res.code == 200 && (!validateNull(res.data)) ) {
                if (res.data.name) {
                    submitObj.name = res.data.name;
                    $("#name").val(submitObj.name);
                }

                if (res.data.sex) {
                    submitObj.sex = res.data.sex;
                    $("#sex").val(submitObj.sex === "1" ? '男' : '女');
                }

                if (res.data.communityId) {
                    submitObj.communityId = res.data.communityId;
                    // 处理小区回显
                    for (var i = 0; i < communityIdItems.length; i++) {
                        if (communityIdItems[i].value === submitObj.communityId) {
                            $("#communityId").val(communityIdItems[i].title);
                            break;
                        }
                    }
                }

                if (res.data.age) {
                    submitObj.age = res.data.age;
                    $("#age").val(submitObj.age);
                }

                if (res.data.idCard) {
                    submitObj.idCard = res.data.idCard;
                    $("#idCard").val(submitObj.idCard);
                }

                if (res.data.phone) {
                    submitObj.phone = res.data.phone;
                    $("#phone").val(submitObj.phone);
                }

                if (res.data.building) {
                    submitObj.building = res.data.building;
                    $("#building").val(submitObj.building);
                }

                if (res.data.room) {
                    submitObj.room = res.data.room;
                    $("#room").val(submitObj.room);
                }

                if (res.data.pictureId) {
                    submitObj.pictureId = res.data.pictureId;
                    // 图片ID数组
                    pictureIdArr = res.data.pictureId.split(",");
                }

                // 处理图片的回显
                if (res.data.pictureUrlList) {
                    var pictureUrlList = JSON.parse(JSON.stringify(res.data.pictureUrlList));
                    for (var i = 0; i < res.data.pictureUrlList.length; i++) {
                        $("#uploaderFiles").append($(tmpl.replace('#url#', baseUrl + pictureUrlList[i])));
                    }
                    $(".weui-uploader__info").text(pictureIdArr.length + "/" + maxCount);
                }

            }
        },
        error: function(res) {
            $.toast(res.message, "error");
        },
        complete: function () {
            // 关闭等待层
            $.hideLoading();
        }
    })

    initImg();
}